# Python Extractor of Wifi Data For Floor Detection
#v_2.0.0_build_20161024

"""

Every Floor:
	Mean, Variance

Over All Floor:
	Weight of Each AP

	Determination of Weight:
		Count on Each Floor
		Variance Over Each Floor -- Error Rate Over Different Floors(KL: log(sigma1/simga2) + (sigma1^2 + (mu1 - mu2)^2)/(2*sigma2^2))



"""


import os
from numpy import *
import numpy as np
import shutil


def genPathlist(dirpath):
	dirlist = os.listdir(dirpath);

	pathlist = [];
	for dirname in dirlist:
		if 'DS_Store' in dirname:
			continue
		if not os.path.isdir(os.path.join(dirpath, dirname)):
			continue
		if 'Floor' in dirname:
			continue
		wifipath = os.path.join(os.path.join(dirpath, dirname), 'wifi.dat');
		if os.path.exists(wifipath):
			pathlist.append(wifipath);
	print "Pathlist; %s" % (pathlist)
	return pathlist


def extractWifi(pathlist,savepath):
	wifilist = getWifiList(pathlist);
	saveWifiList(wifilist, savepath);
	getWifiValue(pathlist, wifilist, savepath);
	return 0


def saveWifiList(wifilist, savepath):
	f = open(os.path.join(savepath,'wifilist.txt'), 'w');
	f.write(",".join(wifilist));
	f.close()


def getWifiList(pathlist):
	wifilist = [];
	for wifipath in pathlist:
		dirname = os.path.dirname(wifipath);
		filelist = os.listdir(dirname);
		for filename in filelist:
			if filename.endswith("wifilist"):
				localwifilist = os.path.join(dirname, filename);
				break;
		f = open(localwifilist);
		l = f.readline();
		f.close()
		wifilist = list(set(wifilist + l.split(',')));
	return wifilist


def getWifiValue(pathlist, wifilist, savepath):
	print "PathList Length: %s" % (len(pathlist))
	for i in range(len(pathlist)):
		wifipath = pathlist[i];
		mat = getWifiValueSingleFile(wifipath, wifilist);
		outputFormat(mat, i , savepath)
	return 0;


def outputFormat(mat, i, savepath):
	f = open(os.path.join(savepath, "floor.data"), 'a');
	for vec in mat:
		str = "%s " % i;
		for ind,num in enumerate(vec):
			if num>0:
				str += "%s:%s " %(ind,num);
		f.write(str);
		f.write("\n");
	f.close();


def getWifiValueSingleFile(wifipath, wifilist):
	dirname = os.path.dirname(wifipath);
	filelist = os.listdir(dirname);
	for filename in filelist:
		if filename.endswith("wifilist") and (not filename.startswith('.')):
			localwifilist = os.path.join(dirname, filename);
			break;
	f = open(localwifilist)
	l = f.readline()
	f.close()
	locallist = l.split(',');
	f = open(wifipath)
	mat = [];
	for l in f:
		vec = [0] * len(wifilist);
		ls = l.split(",");
		for n in range(len(ls)):
			value = float(ls[n]);
			if (value < 1e-3):
				continue;
			ind = wifilist.index(locallist[n]);
			vec[ind] = value;
		mat.append(vec);
	f.close();
	return mat;


def genReadme(pathlist,savepath):
	f = open(os.path.join(savepath, "README.CONF"),'w');
	for i in range(len(pathlist)):
		str = "%s: %s\n" % (i, pathlist[i]);
		f.write(str);
	f.close();


def callFloorDataExtraction():
	prefix = "10100123"
	basepath = "/home/jack/workspace/FloorIdentification/data"
	dirpath = os.path.join(basepath, prefix)
	savepath = "./"+prefix;
	if os.path.exists(savepath):
		pass;
	else:
		os.mkdir(savepath);
	pathlist = genPathlist(dirpath)
	genReadme(pathlist, savepath)
	extractWifi(pathlist, savepath)

callFloorDataExtraction()
